//
//  LDYOAuthViewController.swift
//  李东阳微博
//
//  Created by 李东阳 on 16/4/17.
//  Copyright © 2016年 李东阳. All rights reserved.
//
//App Key：3121261634
//App Secret：105b02ce444d72a7ec54400ccc27a1c9
//授权回调页：http://www.baidu.com/
//取消授权回调页：http://www.weibo.com/
//client_id	true	string	申请应用时分配的AppKey。
//redirect_uri	true	string
//https://www.baidu.com/?code=0bbc9e538d522df136d858daf3742d19


//Optional("https://api.weibo.com/oauth2/authorize")
//Optional("https://api.weibo.com/oauth2/authorize#")
//Optional("https://api.weibo.com/oauth2/authorize")
//Optional("http://www.baidu.com/?code=422bb3e91a34fba020b23baba022e822")
//Optional("https://m.baidu.com/?code=422bb3e91a34fba020b23baba022e822&from=844b&vit=fps")
import UIKit
import SVProgressHUD
import AFNetworking
class LDYOAuthViewController: UIViewController {

    override func loadView() {
        view = webview
        
      webview.delegate = self
        
        let urlString = "https://api.weibo.com/oauth2/authorize?client_id=\(APPKEY)&redirect_uri=\(REDIRECT_URI)"
            //MARK: -  定义一个url

        print(urlString)
        let url = NSURL(string: urlString)
            //MARK: -  定义一个请求

        let request = NSURLRequest(URL: url!)
        
        webview.loadRequest(request)
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()

    setupUI()
    }

        //MARK: -  设置视图
    private  func setupUI(){
    
     view.backgroundColor = UIColor.whiteColor()
    
        setupNaV()
    }
    
    
        //MARK: -  监听方法
    
    
   private func setupNaV(){
        
    
    navigationItem.leftBarButtonItem = UIBarButtonItem(title: "取消", style: UIBarButtonItemStyle.Plain, target: self, action: "cancleWrite")
    
       SVProgressHUD.dismiss()
        
     navigationItem.rightBarButtonItem = UIBarButtonItem(title: "自动填充", style: UIBarButtonItemStyle.Plain, target: self, action: "autoWrite")
        
      navigationItem.title = "微博登陆"
    }

    
 @objc private  func cancleWrite(){
        
        dismissViewControllerAnimated(true) { () -> Void in
            
            print("取消了")
        }
    }
    
 @objc private  func autoWrite(){
    
  
    let jsString = "document.getElementById('userId').value='\(CZWeiboName)';document.getElementById('passwd').value='\(CZWeiboPasswd)'"
    
    webview.stringByEvaluatingJavaScriptFromString(jsString)
        print("自动填充按钮点击啦")
    }
    
    private lazy var webview:UIWebView = UIWebView()
}
extension LDYOAuthViewController:UIWebViewDelegate{

    func webViewDidStartLoad(webView: UIWebView) {
        
        SVProgressHUD.show()
    }
    
    func webViewDidFinishLoad(webView: UIWebView) {
        
        SVProgressHUD.dismiss()
    }
    
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        
//        let urlString = request.URL?.absoluteString
//    
//        urlString?.hasPrefix(REDIRECT_URI)
        if let urlString = request.URL?.absoluteString where   urlString.hasPrefix(REDIRECT_URI){
        
        
            if let q = request.URL?.query{
            

                
             let code = q.substringFromIndex("code=".endIndex)
                

                getUserAccount(code)
                
             
             return false
            }
            
            
            
        }
        
            //MARK: - 判断urlString 前缀是不是我们回调页

        
        return true
    }

}
extension LDYOAuthViewController{

    
    func getUserAccount(code: String){
            //MARK: -   请求的url
        let urlString = "https://api.weibo.com/oauth2/access_token"
        
            //MARK: -  请求参数
        
        
  let parms = [
    
       "client_id": APPKEY,
       "client_secret": APPSECRET,
       "grant_type": "authorization_code",
       "code":code,
       "redirect_uri": REDIRECT_URI
    
        ]
    
        let manager = AFHTTPSessionManager()
        manager.responseSerializer.acceptableContentTypes?.insert("text/plain")
        manager.POST(urlString, parameters: parms, progress: nil, success: { (_ , response) -> Void in
                //Mark --
//            print(response)
            
       
            
            guard let dateDict = response as?[String:AnyObject] else{
            
            print("返回的不是一个字典")
            return
            }
            
            let userAccount:LDYUserAccount = LDYUserAccount(dict: dateDict)
            
//          print(userAccount)
             self.getUserInfo(userAccount)
            
            

            }) { (_ , error) -> Void in
                //Mark --
                print(error)

        }
        
    }
   
    func getUserInfo(userAccount:LDYUserAccount){
    
            //MARK: -   urlString
        let urlString = "https://api.weibo.com/2/users/show.json"
        
        let parms = [
        
            "access_token": userAccount.access_token! ,
            "uid": userAccount.uid!
        ]

        let manager = AFHTTPSessionManager()
        
        manager.GET(urlString, parameters: parms, progress: nil, success: { (_, response) -> Void in
                //Mark --
                print(response)
            guard let responseDate = response as? [String: AnyObject] else{
            
            return
            }
         
            
            userAccount.profile_image_url = responseDate["profile_image_url"] as? String
            
            userAccount.avatar_large = responseDate["avatar_large"] as?String
            
            userAccount.screen_name = responseDate["screen_name"]as?String
            
                   print(userAccount)
            
            LDYUserAccountTools.userAccountTools.saveUserAccount(userAccount)
            
            
            self.dismissViewControllerAnimated(false, completion: { () -> Void in
                    //MARK: -  发送 通知告知appdelegate 帮助我们切换根视图
                NSNotificationCenter.defaultCenter().postNotificationName(swithDefaultVcDefaultCenter, object: nil)
 
                
            })
            
         
            
            }) { (_ , error) -> Void in
                //Mark --
                 print(error)

        }
    
    }

}
